import Taro from '@tarojs/taro'
import React, { useEffect, useState } from 'react'
import { AtGrid } from 'taro-ui'
import Router from 'tarojs-router-next'
import env from '../../../store/env.config'

interface MyGridProps {
  parentId?: number
  userInfo?: any
  refresh: number
}

const MyGrid: React.FC<MyGridProps> = ({ parentId = 0, userInfo, refresh }) => {
  const [dataSource, setDataSource] = useState([])
  useEffect(() => {
    Taro.request({
      url: `${env.domain}/species/list`,
      data: {
        page: 1,
        pageSize: 10000,
        dictType: 'goods',
        parentId: parentId,
        token: userInfo['auth'],
      },
      success: (res) => {
        if (res.data['code'] === 200) {
          let tmpData = res.data?.data?.recode
          let tmpDataSource = [] as any
          tmpData?.map((item) => {
            let iconConfig = {
              value: item.title as string,
              iconInfo: { value: 'sketch', size: 20, color: '#1890ff' },
              key: item.id,
            }
            tmpDataSource.push(iconConfig)
          })
          setDataSource(tmpDataSource)
        }
      },
    })
  }, [parentId, refresh])

  const getGoods = (id: number) => {
    let url = `${env.domain}/goods/list`
    if (id !== 0) {
      url = `${env.domain}/goods/list?speciesId=${id}`
    }
    Taro.request({
      url: url,
      data: {
        page: 1,
        pageSize: 10000,
        token: userInfo['auth'],
      },
      success: (requestData) => {
        if (requestData.data['code'] === 200) {
          Router.navigate({ url: '/pages/goods/goods' }, { data: requestData })
        }
      },
    })
  }

  return (
    <AtGrid
      mode='rect'
      hasBorder={false}
      data={dataSource}
      onClick={(item: any) => {
        getGoods(item.key)
      }}
    />
  )
}

export default MyGrid
